package com.commerce.networkframework.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.commerce.networkframework.R;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);
        textView = findViewById(R.id.text_ok);
        okhttp();
    }

    private void okhttp(){
        //请求参数
        FormBody formBody = new FormBody.Builder()
                .add("key","7b3a2993da15202e95aa1e78e4e0799c")
                .build();
        Request postRequest = new Request.Builder()
                .url("http://apis.juhe.cn/simpleWeather/cityList")
                .post(formBody)
                .build();
        final OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(postRequest);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {
                Log.d("TAG", "onResponse: " +Thread.currentThread().getName());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                      textView.setText(response.body().toString());
                    }
                }); 
            }
        });

    }

}